const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const toml = require('toml')
const yaml = require('yaml')
const json5 = require('json5')

module.exports = {
  // entry: './src/index.js',
  entry: {
    index: './src/index.js',
    another: './src/another-module.js',
  },
  output: {
    path: path.resolve(__dirname, '../dist'), // 借助path模块配置绝对路径
    clean: true, // 打包清理上次的 dist
    // assetModuleFilename: 'images/test.png', // 配置资源打包目录和名称(固定)
    assetModuleFilename: 'images/[contenthash][ext]', // [根据内容生成hash值][扩展名]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html', // 模板文件
      filename: 'app.html', // 输出文件名字
      inject: 'body', // 插入位置 head （默认）和 body
    }),
    new MiniCssExtractPlugin({
      filename: 'styles/[contenthash].css'
    })
  ],
  module: {
    rules: [
      {
        test: /\.png$/,
        type: 'asset/resource',
        generator: {
          // filename: 'images/test.png',
          filename: 'images/[contenthash][ext]',
        }
      }, {
        test: /\.svg$/,
        type: 'asset/inline',
      }, {
        test: /\.txt$/,
        type: 'asset/source'
      }, {
        test: /\.jpg$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 4 * 1024, // 4kb
            // maxSize: 1 * 1024 * 1024, // 1M
          }
        }
      }, {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        type: 'asset/resource',
      },
      {
        test: /\.(css|less)$/,
        // 从右向左 先 用css-loader识别css文件打包没有问题，在使用style-loader放置到页面上
        // use: ['style-loader', 'css-loader', 'less-loader'],
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
      }, {
        test: /\.(csv|tsv)$/,
        use: ['csv-loader'],
      }, {
        test: /\.xml$/,
        use: ['xml-loader'],
      }, {
        test: /\.toml$/,
        type: 'json',
        parser: {
          parse: toml.parse
        }
      }, {
        test: /\.yaml$/,
        type: 'json',
        parser: {
          parse: yaml.parse
        }
      }, {
        test: /\.json5$/,
        type: 'json',
        parser: {
          parse: json5.parse
        }
      }, {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  }
}